#pragma once
#include<iostream>
#include<string>
#include<cstring>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<sys/stat.h>
#include "log.hpp"
#include "protocol.hpp"

#define NUM 1024
namespace Client
{
    enum
    {
        USAGE_ERR = 1,
        SOCKET_ERR,
        BIND_ERR,
        LISTEN_ERR,
        ACCEPT_ERR
    };
    class TcpClient
    {
    public:
        TcpClient(const uint16_t &port, const std::string &ip)
            : ServerIp_(ip), ServerPort_(port), sock_(-1)
        {}
        void InitClient()
        {
            //1.创建套接字
            sock_ = socket(AF_INET,SOCK_STREAM,0);//创建套接字
            if(sock_ < 0)
            {
                LogMessage(FATAL,"cteat socket fail");
                exit(SOCKET_ERR);
            }
            LogMessage(NORMAL,"create socket success");


        }
        void start()
        {
            struct sockaddr_in server;
            bzero(&server, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_addr.s_addr = inet_addr(ServerIp_.c_str());
            server.sin_port = htons(ServerPort_);
            if(connect(sock_,(struct sockaddr*)&server,sizeof(server)) < 0) //请求连接！
            {
                LogMessage(FATAL,"socket connect fail");
            }
            else
            {
                //可以开始通信！
                LogMessage(NORMAL, "socket connect success!");
                std::string line;
                std::string inbuffer;
                while(true)
                {
                    std::cout << "mycal>>> ";
                    getline(std::cin,line);//line里面没有\n

                    ////这里对命令行的输入进行处理！

                    Request req = ParseLine(line);

                    std::string content;
                    req.Serialize(&content);
                    //将结构化数据转化为字符串！
                    LogMessage(NORMAL,"Serialize success!");

                    std::string send_string = enLength(content);
                    //将其编程变成完整的报文！
                    LogMessage(NORMAL,"enlenth success!");

                    send(sock_,send_string.c_str(),send_string.size(),0);

                    LogMessage(NORMAL, "send success!");
                    ////////////////////////////////////////////////////////////////////
                    //这部分是TCP需要的！UDP是不需要这部分的！因为UDP是数据报收到的数据一定是完整的！

                    std::string Package,text;
                    if (!recvPackage(sock_, inbuffer, &Package))
                    {
                        LogMessage(ERROR, "recv fail!");
                        continue;
                    }

                    LogMessage(NORMAL, "get Package success!");

                    //package里面有完整的报文！我们要获取有效载荷！
                    if(!deLength(Package,&text)) continue;//获取报文内容放入text

                    LogMessage(NORMAL, "delength success!");

                    /////////////////////////////////////////////////////////////////////

                    //进行反序列化！ 
                    Respone resp;
                    resp.Deserialize(text);//获取到结果！
                    LogMessage(NORMAL, "Deserrialize success!");

                    std::cout <<"exitCode: " <<resp.exitcode_ << std::endl;
                    std::cout << "result: " << resp.result_ << std::endl;
                }
            }
        }

        Request ParseLine(const std::string& line)//这个函数专门用来处理命令行的IO,是建议版本的状态机！根据字符串状态对字符串进行处理！
        {
            // ‘1+1’ ‘123*1231’ "12\0"
            int status =0;//0 ：表示操作符之前！1:表示碰到了字符！ 2:表示碰到了操作符之后！
            int i = 0;
            int cnt = line.size();
            std::string left,right;
            char op;
            while(i < cnt)
            {
                switch(status)
                {
                case 0:
                {
                    if (!isdigit(line[i])) // 判断一个字符是不是数字
                    {
                        op = line[i];     
                        status = 1;
                    }
                    else
                        left.push_back(line[i++]);
                }
                    break;
                case 1:
                    i++;
                    status  =2;
                    break;
                case 2:
                    right.push_back(line[i++]);
                    break;
                }
            }
            std::cout << std::stoi(left) << " " << std::stoi(right) << " " << op << std::endl;
            return Request(std::stoi(left),std::stoi(right),op);

        }
        ~TcpClient()
        {
            if(sock_ >= 0) close(sock_);//这里也要释放防止文件描述符泄漏！
        }
    private:
        int sock_;//套接字
        std::string ServerIp_;//服务器的ip
        uint16_t ServerPort_;//服务器的端口！
    };
}